package com.argticling.security;

import java.util.Collection;
import java.util.ArrayList;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;

import com.argticling.dao.impl.UserDAOImplementation;
import com.argticling.model.User;
import com.google.code.facebookapi.schema.UpdateDecodeIDsResponse;

public class MyFilter implements AuthenticationProvider {

	private static final String DEFAULT_FILTER_PROCESSES_URL = "/accessDenied.jsp";
	private static final String POST = "POST";

	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		String password = (String) authentication.getCredentials();
		String username = (String) authentication.getPrincipal();
		boolean aut = checkAuthentication(username, password);
		if (!aut) {
			return null;
		} else {
			String role = getRole(username); 
			Collection auth = new ArrayList();
			auth.add(new GrantedAuthorityImpl(role));
			return new UsernamePasswordAuthenticationToken(username, password,	auth);
		}
	}

	private String getRole(String username) {
		UserDAOImplementation userDao = new UserDAOImplementation();
		return userDao.getUserByName(username).getRole();
	}

	private boolean checkAuthentication(String username, String pass) {
		UserDAOImplementation userDao = new UserDAOImplementation();
		if(userDao.checkIfUserExists(username, pass)){
			return true;
		}
		return false;
	}

	public boolean supports(Class<? extends Object> arg0) {
		return true;
	}

}

